package hadoop.mapreduce.mapjoin;


import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;

/**
 * 相当于一个MapTask
 */
public class TableMapper extends Mapper<LongWritable, Text, TableBean, NullWritable> {

    FSDataInputStream fis;
    BufferedReader reader;
    HashMap<String,String> pdMap=new HashMap();
    /**
     * MapTask开始前执行一次
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        //取出缓存中所有的文件
        URI[] cacheFiles = context.getCacheFiles();
        //当前场景只存了一个文件,所以取第一个的路径就行
        Path path=new Path(cacheFiles[0]);
        //获取文件系统对象,并开流
        FileSystem fs = FileSystem.get(context.getConfiguration());
        fis = fs.open(path);
        //通过包装流转换为高效reader,方便按行读取
        reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        //逐行读取pd.txt，按行处理
        String line;
        while (StringUtils.isNotEmpty(line = reader.readLine())) {
            //切割一行
            //01	小米
            String[] split = line.split("\t");
            pdMap.put(split[0], split[1]);
        }
    }

    /**
     * 处理order.txt
     * @param key
     * @param value
     * @param context
     * @throws IOException
     * @throws InterruptedException
     * id   pid  amount
     * 1001	01	 1
     */
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] split = value.toString().split("\t");
        TableBean tableBean = new TableBean();
        tableBean.setId(split[0]);
        tableBean.setAmount(Long.parseLong(split[2]));
        tableBean.setpName(pdMap.get(split[1]));
        context.write(tableBean,NullWritable.get());
    }

    /**
     * 关流
     * MapTask结束后执行一次
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        IOUtils.closeStream(fis);
        IOUtils.closeStream(reader);
    }
}
